import {
	find,
	get,
	isArray,
	isFunction
} from "lodash";
import {
	ElMessageBox
} from "element-plus";

const defaultWorkbeanchTab = {
	id: undefined,
	type: undefined,
	title: undefined,
	data: undefined,
	edited: false,
	fixed:false,
	show:true,
	component: undefined,
	ref:undefined
};
class WorkbeanchTab {
	constructor(prop) {
		for (let key in defaultWorkbeanchTab) {
			this[key] = get(prop, key, defaultWorkbeanchTab[key]);
		}
		this.setRef = (el) => {
			this.ref = el;
		}
	}
}
class WorkbeanchTabs {
	constructor(prop) {
		const tabs = get(prop, "tabs", []);
		this.activeTab = get(prop, "activeTab");
		this.activeTabData=get(prop,"activeTabData")
		if (this.validateTabs(tabs)) {
			this.tabs = tabs;
		} else {
			this.tabs = [];
		}
	}
	validateTab(tab) {
		const isValid = tab && tab instanceof WorkbeanchTab;
		if (!isValid) {
			console.warn(`tab[${tab}]不符合规范`);
		}
		return isValid;
	}
	validateTabs(tabs) {
		const isValid =
			isArray(tabs) &&
			tabs.every(item => {
				return this.validateTab(item);
			});
		if (!isValid) {
			console.warn(`tabs不符合规范`);
		}
		return isValid;
	}
	addTab(tab) {
		if (this.validateTab(tab)) {
			const oldTab = find(this.tabs, item => item.id === tab.id);
			if (oldTab) {
				this.switchTab(oldTab.id);
			} else {
				this.tabs.push(tab);
				this.switchTab(tab.id);
			}
		}
	}
	removeTab(id) {
		return new Promise((resolve, reject) => {
			if (!id || this.tabs.length <= 0) {
				resolve();
				return;
			}
			let targetIndex = this.tabs.findIndex(item => {
				return item.id === id;
			});
			const tab = this.findTabById(id);
			if(!tab || tab.fixed){
				resolve();
				return;
			}
			const removeCurrentTab = () => {
				if (id === this.activeTab) {
					let nextTab = this.findNextTabById(id);
					if (nextTab) {
						this.switchTab(nextTab.id);
					} else {
						this.tabs = [];
						this.activeTab = undefined;
						this.activeTabData=undefined
					}
				}
				this.removeTabWithRange(targetIndex, 1);
			};
			if (targetIndex !== -1) {
				if (tab.edited) {
					ElMessageBox.confirm(
							'任务未保存，确定要关闭吗？',
							'Warning', {
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							}
						)
						.then(async () => {
							await this.updateTasks([tab]);
							removeCurrentTab();
							resolve("asyncRemove");
						})
						.catch(() => {
							if (e.length === 0) {
								removeCurrentTab();
							}
							resolve();
						})
				} else {
					removeCurrentTab();
					resolve();
				}
			} else {
				reject(`不存在的tab id:${id}`);
			}
		});
	}
	removeTabWithRange(start = 0, end = 0) {
		this.tabs.splice(start, end);
	}
	removeLeftTab(id) {
		return new Promise((resolve, reject) => {
			if (!id || this.tabs.length <= 1) {
				resolve();
				return;
			}
			const {
				activeTab
			} = this;
			let targetIndex = this.tabs.findIndex(item => {
				return item.id === id;
			});
			if (targetIndex !== -1) {
				const willRemoveTabs = this.tabs.filter((item, index) => {
					return index < targetIndex;
				});
				const needConfirm = willRemoveTabs.some(item => {
					return item.edited;
				});
				
				const removeLeftTabs = () => {
					const activeIndex = this.tabs.findIndex(item => {
						return item.id === activeTab;
					});
					this.removeTabWithRange(0, targetIndex);
					//判断activeTab是否在删除范围内
					activeIndex < targetIndex && this.switchTab(id);
				};
				if (needConfirm) {
					ElMessageBox.confirm(
							'任务未保存，确定要关闭吗？',
							'Warning', {
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							}
						)
						.then(async () => {
							await this.updateTasks(willRemoveTabs);
							removeLeftTabs();
							resolve("asyncRemove");
						})
						.catch(() => {
							if (e.length === 0) {
								removeLeftTabs();
							}
							resolve();
						})
				} else {
					removeLeftTabs();
					resolve();
				}
			} else {
				reject(`不存在的tab id:${id}`);
			}
		});
	}
	removeRightTab(id) {
		return new Promise((resolve, reject) => {
			const tabsLen = this.tabs.length;
			if (!id || tabsLen <= 1) {
				resolve();
				return;
			}
			const {
				activeTab
			} = this;
			let targetIndex = this.tabs.findIndex(item => {
				return item.id === id;
			});
			if (targetIndex !== -1) {
				const willRemoveTabs = this.tabs.filter((item, index) => {
					return index > targetIndex;
				});
				const needConfirm = willRemoveTabs.some(item => {
					return item.edited;
				});
				const removeRightTabs = () => {
					const activeIndex = this.tabs.findIndex(item => {
						return item.id === activeTab;
					});
					const removeCount = tabsLen - targetIndex - 1;
					this.removeTabWithRange(targetIndex + 1, removeCount);
					//判断activeTab是否在删除范围内
					activeIndex > targetIndex && this.switchTab(id);
				};
				if (needConfirm) {
					ElMessageBox.confirm(
							'任务未保存，确定要关闭吗？',
							'Warning', {
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							}
						)
						.then(async () => {
							await this.updateTasks([tab]);
							removeRightTabs();
							resolve("asyncRemove");
						})
						.catch(() => {
							if (e.length === 0) {
								removeRightTabs();
							}
							resolve();
						})
				} else {
					removeRightTabs();
					resolve();
				}
			} else {
				reject(`不存在的tab id:${id}`);
			}
		});
	}
	removeOtherTab(id) {
		return new Promise((resolve, reject) => {
			if (!id || this.tabs.length <= 1) {
				resolve();
				return;
			}
			const tab = this.findTabById(id);
			if (tab) {
				const willRemoveTabs = this.tabs.filter(item => {
					return item.id !== id;
				});
				const needConfirm = willRemoveTabs.some(item => {
					return item.edited;
				});
				const removeOtherTabs = () => {
					this.tabs = [tab];
					this.switchTab(id);
				};
				if (needConfirm) {
					ElMessageBox.confirm(
							'任务未保存，确定要关闭吗？',
							'Warning', {
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							}
						)
						.then(async () => {
							await this.updateTasks(willRemoveTabs);
							removeOtherTabs();
							resolve("asyncRemove");
						})
						.catch(() => {
							if (e.length === 0) {
								removeOtherTabs();
							}
							resolve();
						})

				} else {
					removeOtherTabs();
					resolve();
				}
			} else {
				reject(`不存在的tab id:${id}`);
			}
		});
	}
	async updateTasks(tabs = []) {
		if (!tabs || tabs.length <= 0) return;
		const taskQueue = [];
		tabs.forEach(item => {
			if (item.edited && item.taskRef && isFunction(item.taskRef.updateTask)) {
				taskQueue.push(item.taskRef.updateTask(true));
			}
		});
		return Promise.all(taskQueue);
	}
	switchTab(id) {
		if (!id) return;
		const tabExisted = find(this.tabs, item => item.id === id);
		tabExisted && (this.activeTab = id);
		this.activeTabData=tabExisted;
		tabExisted.show = true;
		this.tabs.forEach(item => {
			if(item.id === id){
				item.show = true;
			}else{
				item.show = false
			}
		});
	}
	clearTabs() {
		this.tabs = [];
		this.activeTab = undefined;
		this.activeTabData=undefined
	}
	findTabById(id) {
		return this.tabs.find(item => item.id === id);
	}
	findNextTabById(id, allowReverse = true) {
		const index = this.tabs.findIndex(item => item.id === id);
		if (index !== -1) {
			const nextTab = this.tabs[index + 1];
			if (nextTab) {
				return nextTab;
			} else if (allowReverse) {
				const prevTab = this.tabs[index - 1];
				return prevTab;
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}
export {
	WorkbeanchTab,
	WorkbeanchTabs
};
